package com.lkd.http.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.wxpay.plus.WXConfig;
import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.OrderService;
import com.lkd.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPayTemplate wxPayTemplate;

    @Autowired
    private MqttProducer mqttProducer;

    @PostMapping("/requestPay")
    public Map requestPay(@RequestBody PayVO payVO){
        //参数校验
        if(StringUtils.isBlank(payVO.getInnerCode()) || StringUtils.isBlank(payVO.getSkuId())){
            throw new LogicException("参数校验失败");
        }

        OrderEntity orderEntity = orderService.requestPay(payVO);

        //封装支付请求对象调用支付
        var param=new WxPayParam();
        param.setBody(orderEntity.getSkuName());
        param.setOutTradeNo(orderEntity.getOrderNo());
        param.setTotalFee(orderEntity.getPrice());
        param.setOpenid(payVO.getOpenId());
        //前端需要完整的返回结果
        Map<String, String> result = wxPayTemplate.requestPay(param);

        //发送消息 $delayed/时间/topic名
        OrderCheck orderCheck = new OrderCheck();
        orderCheck.setOrderNo(orderEntity.getOrderNo());
        orderCheck.setInnerCode(orderEntity.getInnerCode());
        try {
            mqttProducer.send("$delayed/10/" + TopicConfig.ORDER_CHECK_TOPIC,2,orderCheck);
        } catch (JsonProcessingException e) {
            log.error("下单流程发送消息失败",e);
        }

        return result;
    }


    /**
     * 微信支付回调接口
     * @param request
     * @return
     */
    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response){

        try {
            Map<String, String> result = wxPayTemplate.validPay(request.getInputStream());
            if("SUCCESS".equals( result.get("code") )){  //返回码成功
                String orderSn= result.get("order_sn");//获取订单号
                log.info("支付成功，修改订单状态和支付状态，订单号：{}",orderSn);

                //设置订单状态为已支付
                //设置流水号
                orderService.update(Wrappers.<OrderEntity>lambdaUpdate()
                        .eq(OrderEntity::getOrderNo,orderSn)
                        .set(OrderEntity::getPayStatus, VMSystem.PAY_STATUS_PAYED)
                        .set(OrderEntity::getStatus,VMSystem.ORDER_STATUS_PAYED)
                        .set(OrderEntity::getThirdNo,result.get("transaction_id"))
                );

                //出货(暂不完成)
            }
            //给微信支付一个成功的响应
            response.setContentType("text/xml");
            response.getWriter().write(WXConfig.RESULT);
        }catch (Exception e){
            log.error("支付回调处理失败",e);
        }
    }
}
